/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nmp.controller;

import business.service.FBClientService;
import business.service.GGClientService;
import com.nmp.common.CommonUtil;
import com.nmp.common.RenderModel;
import com.nmp.common.UserData;
import com.nmp.model.SessionModel;
import com.nmp.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class RegisterController extends HttpServlet {

    private static final Logger logger = Logger.getLogger(RegisterController.class);


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("RegisterController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/ajax-register":
                content = ajaxRegister(req, resp);
                break;
            case "/ajax-register-fb":
                content = ajaxRegisterFacebook(req, resp);
                break;
            case "/ajax-register-gg":
                content = ajaxRegisterGoogle(req, resp);
                break;
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }

    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        TemplateDataDictionary dic = TemplateDictionary.create();

        try {
            dic.setVariable("HEADER", CommonUtil.getHeader());
            dic.setVariable("FOOTER", CommonUtil.getFooter());
//            dic.setVariable("MENU", CommonUtil.getMenu(req));

            Template template = RenderModel.getCTemplate("register_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("RegisterController.renderIndexPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }

    private String ajaxRegister(HttpServletRequest req, HttpServletResponse resp) {
        String content;
        int error = 0;
        String msg = "Đăng kí thành công.";
        Map<String, String> data = new HashMap<>();
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        try {
            String name = req.getParameter("name") != null ? req.getParameter("name") : "";
            String mail = req.getParameter("mail") != null ? req.getParameter("mail") : "";
            String pass = req.getParameter("pass") != null ? req.getParameter("pass") : "";

            if (error == 0 && mail.equalsIgnoreCase("")) {
                msg = "Email không được trống.";
                error = -2;
            }

            if (error == 0 && !CommonUtil.validateEmail(mail)) {
                msg = "Email không hợp lệ";
                error = -2;
            }

            UserModel userModel = UserModel.getInstance();
            if (error == 0 && userModel.checkEmailExist(mail)) {
                msg = "Email đã tồn tại";
                error = -2;
            }

            if (error == 0 && pass.equalsIgnoreCase("")) {
                msg = "Mật khẩu không được trống.";
                error = -3;
            }

            if (error == 0 && pass.length() < 6) {
                msg = "Mật khẩu không hợp lệ.";
                error = -3;
            }

            if (error == 0 && name.length() > 100) {
                msg = "Họ tên quá dài.";
                error = -4;
            }

            if (error == 0 && name.equalsIgnoreCase("")) {
                msg = "Họ tên không được trống.";
                error = -4;
            }

            if (error == 0) {
                UserData userData = new UserData(name, mail, pass);
                String userId = userModel.addUser(userData);
                data.put("id", userId);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    private String ajaxRegisterFacebook(HttpServletRequest req, HttpServletResponse resp) {
        String content;
        int error = -1;
        String msg = "Invalid AccessToken";
        Map<String, String> data = new HashMap<>();
        
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        try {
            String accessToken = req.getParameter("accessToken");
            
            FBClientService fbClient = FBClientService.getInstance();
            UserData userData = fbClient.inspectAccessTokens(accessToken);
            if (userData != null) {
                String fb_user_id = userData.getApp_user_id();
                UserModel userModel = UserModel.getInstance();
                boolean isExistAppId = userModel.checkAppUserExist(fb_user_id);
                if (isExistAppId) { 
                    SessionModel.getInstance().setSession(fb_user_id, req, resp);
                } else { 
                    SessionModel.getInstance().setSession(fb_user_id, req, resp);
                    String id = fbClient.createFBAccount(userData);
                    data.put("id", id);
                }
                msg = "Đăng kí thành công.";
                error = 0;
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    private String ajaxRegisterGoogle(HttpServletRequest req, HttpServletResponse resp) {
        String content;
        int error = -1;
        String msg = "Invalid AccessToken";
        Map<String, String> data = new HashMap<>();
        
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        try {
            String accessToken = req.getParameter("accessToken");
            GGClientService ggClient = GGClientService.getInstance();
            UserData userData = ggClient.inspectAccessTokens(accessToken);
            if (userData != null) {
                String gg_user_id = userData.getApp_user_id();
                UserModel userModel = UserModel.getInstance();
                boolean isExistAppId = userModel.checkAppUserExist(gg_user_id);
                if (isExistAppId) {
                    SessionModel.getInstance().setSession(gg_user_id, req, resp);
                } else { 
                    SessionModel.getInstance().setSession(gg_user_id, req, resp);
                    String id = ggClient.createGGAccount(userData);
                    data.put("id", id);
                }
                msg = "Đăng kí thành công.";
                error = 0;
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    
}
